package com.ib.review.controller;

import com.ib.review.base.response.JsonResult;
import com.ib.review.pojo.dto.ExternalParam;
import com.ib.review.service.ExternalService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Paths;
@RestController
@RequestMapping("/review/external")
public class ExternalController {

    private final ExternalService externalService;
    public ExternalController(ExternalService externalService) {
        this.externalService = externalService;
    }

    @PostMapping("upload")
    public JsonResult<String> upload(@RequestParam("file") MultipartFile file, ExternalParam param) {
        String uuidName = externalService.upload(file, param);
        return JsonResult.ok(uuidName);
    }

    @GetMapping("download")
    public ResponseEntity<byte[]> download(@RequestParam("filePath") String filePath) {
        byte[] fileBytes = externalService.download(filePath);

        // 从路径中提取文件名
        String fileName = Paths.get(filePath).getFileName().toString();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", fileName);

        return ResponseEntity.ok().headers(headers).body(fileBytes);
    }
}
